/**
 * @FileName: BleDeviceListAdapter.java
 * @Package:com.bdtop.dbl.ui.adapters
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-28
 * @version V1.0
 */

package com.bdtop.dbl.ui.adapters;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: BleDeviceListAdapter
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-28
 */
public class BleDeviceListAdapter extends ArrayListAdapter<BluetoothDevice> {

	/**
	 * @param context
	 */

	public BleDeviceListAdapter(Activity context) {
		super(context);
		mList = new ArrayList<BluetoothDevice>();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ViewHolder holder;

		if (null == row) {
			row = LayoutInflater.from(mContext).inflate(R.layout.listitem_ble_device, null);

			holder = new ViewHolder();
			holder.deviceName = (TextView) row.findViewById(R.id.device_name);
			holder.deviceAddress = (TextView) row.findViewById(R.id.device_address);

			row.setTag(holder);
		} else {
			holder = (ViewHolder) row.getTag();
		}

		BluetoothDevice device = mList.get(position);

		String mac = device.getAddress();
		String imei = Preferences.getImeiForMac(mac);
		if (DBLApplication.getInstance().deviceInfoList != null && !TextUtils.isEmpty(imei)) {
			boolean find = false;
			for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
				if (di.imei.equals(imei)) {
					holder.deviceName.setText(di.name);
					find = true;
					break;
				}
			}
			
			if(!find){
				holder.deviceName.setText(device.getName());
			}
		} else {
			holder.deviceName.setText(device.getName());
		}

		holder.deviceAddress.setText(device.getAddress());

		return row;
	}

	public void addDevice(BluetoothDevice device) {
		if (!mList.contains(device)) {
			mList.add(device);
			notifyDataSetChanged();
		}
	}

	public void clearDevice() {
		mList.clear();
	}

	public List<BluetoothDevice> getDeviceList() {
		return mList;
	}

	static class ViewHolder {
		TextView deviceName;
		TextView deviceAddress;
	}
}
